<%@ page contentType="text/html; charset=ISO-8859-1"%>
<%@ page import="java.util.*"%>
<%@ page import="java.io.*"%>
<%@ page import="java.net.*"%>
<%@ include file="/html/template/template.html"%>

<%
/*
 * This software is provided under the terms
 * of GNU Lesser GPL License. You may not use
 * this file except in compliance with the license. If you need a copy of the license,
 * please go to http://www.gnu.org/copyleft/lesser.html. 
 * This code uses the SpagoBI 2.3 SDK. 
 
 * @author Fabio D'Ovidio
 
*/

// retrieving username and password
String user = request.getParameter("userID");
String password = request.getParameter("password");

%>

<script type="text/javascript">
    //<![CDATA[

var execCrossNavigation = function(iframeId, docLabel, parameters){
//alert('iframeId: ' + '[' + iframeId + ']\n' + 'docLabel: ' + '[' + docLabel + ']\n' + '\n' + 'parameters: ' + '[' + parameters + ']\n');
var role = "/" + this.role;
var spagobiDocIframe = "<center><iframe height='700px' width='900px' src="+Sbi.sdk.services.baseUrl.protocol + "://" + Sbi.sdk.services.baseUrl.host + ":" + Sbi.sdk.services.baseUrl.port + "/" + Sbi.sdk.services.baseUrl.contextPath + "/" + Sbi.sdk.services.baseUrl.controllerPath+"?NEW_SESSION=true&PAGE=ExecuteBIObjectPage&MODALITY=SINGLE_OBJECT_EXECUTION_MODALITY&ROLE="+ role +"&TOOLBAR_VISIBLE=true&SLIDERS_VISIBLE=true&OBJECT_LABEL="+docLabel+parameters+ "&style='height:500px; width:100%'"  + "</iframe></center>";
Ext.getCmp('infotable').body.dom.innerHTML = spagobiDocIframe;    
};
    
Sbi.sdk.services.setBaseUrl({
	        protocol: 'http'     
	        , host: 'localhost'
	        , port: '8080'
	        , contextPath: 'SpagoBI'
	        , controllerPath: 'servlet/AdapterHTTP'  
  });

var DashboardsMap = 
	{

    onPopupClose: function(evt) {
            selectControl.unselect(selectedFeature);
            
        },         
    
    onFeatureUnselect: function (feature) {
            map.removePopup(feature.popup);
            feature.popup.destroy();
            feature.popup = null;
            var infoPanel = Ext.getCmp('infotable');
            if(infoPanel.body){
            infoPanel.body.dom.innerHTML = '';
            }
        },
      
     infotab: function(){
     
     Ext.getCmp('tab').setActiveTab('infotable');
     
     }   
    }    

var indic = new Array(this.map.indicators.length);
		for(var i= 0, len = indic.length; i < len; i++){
		
      indic[i] = this.map.indicators[i];
		} 
    
    var url = this.map.url;
    var analysis = this.map.analysis;
    var layername = this.map.layer;
    var mpname = this.map.mapname;
    var server = this.map.geojsonUrl;
    var document1Label = this.map.document1Label;
    var listeners = this.map.listeners;
    var parameters = this.map.parameters;
    var mapwidth = this.map.width;
    var mapheight = this.map.height;

    var feautreInfo = this.map.feautreInfo;
    
    var getInfo = function(feature) {
    var info = "";
          for(var i=0; i<feautreInfo.length; i++){
          
            info = info+"<b>"+ feautreInfo[i][0] +"</b>: " + feature.attributes[feautreInfo[i][1]] + "<br />";                        
                
            
          
          } 
                return info;
    };
    
    var document2Label = this.map.document2Label;
    var document2Listeners = this.map.document2Listeners;
    var document2Parameters = this.map.document2Parameters;
    var lon = this.map.initPosLon;
    var lat = this.map.initPosLat;
    var zoom = this.map.initZoom;
    var layer_name = this.map.layer_name;
    var extwindow = this.map.window;
    var businessId = this.map.businessId;
    var label = this.map.spagobiDataset;
    var geoid = this.map.geoId;
    var role = this.map.role;
    var dispToolbar1 = this.map.dispToolbar1;
    var dispSlide1 = this.map.dispSlide1;
    var dispToolbar2 = this.map.dispToolbar2;
    var dispSlide2 = this.map.dispSlide2;

    execDoc = function(docLab, role, params, dispToolbar, dispSlide,frameId) {
		    var html = Sbi.sdk.api.getDocumentHtml({
				documentLabel: docLab
				, executionRole: "/" + role
				, parameters: params 
          
				, displayToolbar: dispToolbar
				, displaySliders: dispSlide
				, iframe: {
              id: frameId,
              height: '100%'
		    		, width: '100%'
					, style: 'border: 0px;'
				}
			});
		    
        return html;
        
		};
    

    
Ext.onReady(function(){
    
      var user = '<%=user%>';
			var password = '<%=password%>';
      var cb = function(result, args, success) {
		        
      if(success === true) {

    
    start_map(lon,lat,zoom);
    
    
    if (analysis == "prop"){ 
    
     var propSymbolLayer = [propSymbolLayer];
      propSymbolLayer = new OpenLayers.Layer.Vector(layer_name, {
          'visibility': false,
          
          'styleMap': new OpenLayers.StyleMap({
              'select': new OpenLayers.Style(
                  {'strokeColor': 'red', 'cursor': 'pointer'}
              )
          })
      });

    map.addLayers([propSymbolLayer]);

    var p = new Object();
    p.desc=['desc'];
    for (var i=0; i<parameters.length; i++){
                                      
                                      param = parameters[i][1];

                                      desc = parameters[i][0];
                                      
                                      p[desc] = param;

                                      }
                                      
    var p2 = new Object();
    p2.desc=['desc'];
    for (var i=0; i<document2Parameters.length; i++){
                                      
                                      param = document2Parameters[i][1];

                                      desc = document2Parameters[i][0];
                                      
                                      p2[desc] = param;

                                      }
                                      
                                      
                                      
    
    var selectPropSymbol2 = selectControl = new OpenLayers.Control.SelectFeature(propSymbolLayer,
                {onSelect: (function(feature){
          
                                  selectedFeature = feature;
                                  content =   
                                      "<div style='font-size:.8em'>"+getInfo(feature);
                                 
                                      
                                      for (var i=0; i<listeners.length; i++){
                                      
                                      param = feature.attributes[listeners[i][1]];

                                      desc = listeners[i][0];
                                      
                                      p[desc] = param;

                                      }
  /*    for (var i in p)
	{
		alert('p[\''+i+'\'] is ' + p[i])
	}
  */

                                      for (var i=0; i<document2Listeners.length; i++){
                                      
                                      param = feature.attributes[document2Listeners[i][1]];

                                      desc = document2Listeners[i][0];
                                      
                                      p2[desc] = param;

                                      }
                         
                                     spagobiContent = p;
                                     
                                     spagobiContent2 = p2;
       

                                  var link = '<center><font size="1" face="Verdana"><a href="#" onclick="DashboardsMap.infotab();' + "Ext.getCmp('infotable').body.dom.innerHTML" + ' = execDoc(document2Label, role, spagobiContent2, dispToolbar2, dispSlide2, document2Label)";>' + 'Dettagli</a></font></center>';

                                  popup = new OpenLayers.Popup.FramedCloud("chicken", 
                                          feature.geometry.getBounds().getCenterLonLat(),
                                          null,
                                          content + link + execDoc(document1Label, role, spagobiContent, dispToolbar1, dispSlide1, document1Label),
                                          null, true, DashboardsMap.onPopupClose);
                                  feature.popup = popup;
                                  map.addPopup(popup);
            

          }), 
                 onUnselect: DashboardsMap.onFeatureUnselect}
          );
    
 
    map.addControl(selectPropSymbol2); 
    selectPropSymbol2.activate();

      var geostatistic = new mapfish.widgets.geostat.ProportionalSymbol({
            'map': map,
            'layer': propSymbolLayer,
            'indicators': indic,
            'url': '/SpagoBIGeoReportEngine/MapOl?layer=' + layername + '&server=' + server + '&userID=' + '<%=user%>' + '&label=' + label + '&businessId=' + businessId + '&geoid=' + geoid,
            'loadMask' : {msg: 'Proportional Symbols analysis...', msgCls: 'x-mask-loading'},
            'legendDiv' : 'myChoroplethLegendDiv',
            'featureSelection': false
        });
        
        
    }

    else if (analysis == "chorop"){
    
    
    choroplethLayer = new OpenLayers.Layer.Vector(layer_name, {
          'visibility': false,
          'styleMap': new OpenLayers.StyleMap({
              'default': new OpenLayers.Style(
                  OpenLayers.Util.applyDefaults(
                      {'fillOpacity': 0.5},
                      OpenLayers.Feature.Vector.style['default']
                  )
              ),
              'select': new OpenLayers.Style(
                  {'strokeColor': 'red', 'cursor': 'pointer'}
              )
          })
      });
     
    
    map.addLayer(choroplethLayer);
        
    var p = new Object();
    p.desc=['desc'];
    for (var i=0; i<parameters.length; i++){
                                      
                                      param = parameters[i][1];

                                      desc = parameters[i][0];
                                      
                                      p[desc] = param;

                                      }
                                      
    var p2 = new Object();
    p2.desc=['desc'];
    for (var i=0; i<document2Parameters.length; i++){
                                      
                                      param = document2Parameters[i][1];

                                      desc = document2Parameters[i][0];
                                      
                                      p2[desc] = param;

                                      }
                                      
                                      
                                      
    
    var selectPropSymbol2 = selectControl = new OpenLayers.Control.SelectFeature(choroplethLayer,
                {onSelect: (function(feature){
          
                                  selectedFeature = feature;
                                  content =   
                                      "<div style='font-size:.8em'>"+getInfo(feature);
                                 
                                      
                                      for (var i=0; i<listeners.length; i++){
                                      
                                      param = feature.attributes[listeners[i][1]];

                                      desc = listeners[i][0];
                                      
                                      p[desc] = param;

                                      }
  /*    for (var i in p)
	{
		alert('p[\''+i+'\'] is ' + p[i])
	}
  */

                                      for (var i=0; i<document2Listeners.length; i++){
                                      
                                      param = feature.attributes[document2Listeners[i][1]];

                                      desc = document2Listeners[i][0];
                                      
                                      p2[desc] = param;

                                      }
                         
                                     spagobiContent = p;
                                     
                                     spagobiContent2 = p2;
       

                                  var link = '<center><font size="1" face="Verdana"><a href="#" onclick="DashboardsMap.infotab();' + "Ext.getCmp('infotable').body.dom.innerHTML" + ' = execDoc(document2Label, role, spagobiContent2, dispToolbar2, dispSlide2, document2Label)";>' + 'Dettagli</a></font></center>';

                                  popup = new OpenLayers.Popup.FramedCloud("chicken", 
                                          feature.geometry.getBounds().getCenterLonLat(),
                                          null,
                                          content + link + execDoc(document1Label, role, spagobiContent, dispToolbar1, dispSlide1, document1Label),
                                          null, true, DashboardsMap.onPopupClose);
                                  feature.popup = popup;
                                  map.addPopup(popup);
            

          }), 
                 onUnselect: DashboardsMap.onFeatureUnselect}
          );
      
    
    map.addControl(selectPropSymbol2); 
    selectPropSymbol2.activate();
      
      var geostatistic = new mapfish.widgets.geostat.Choropleth({
            'map': map,
            'layer': choroplethLayer,
            'indicators': indic,
            //'url': 'http://' + server + '/geoserver/wfs?request=GetFeature&typename=topp:'+ layername + '&outputformat=json&version=1.0.0',
            'url': '/SpagoBIGeoReportEngine/MapOl?layer=' + layername + '&server=' + server + '&userID=' + '<%=user%>' + '&label=' + label + '&businessId=' + businessId + '&geoid=' + geoid,
            'loadMask' : {msg: 'Choropleths analysis...', msgCls: 'x-mask-loading'},
            'legendDiv' : 'myChoroplethLegendDiv',
            'featureSelection': false,
            'listeners': {}
        });
  
    }
      
   else {Ext.Msg.alert( 'Status', 'No analysis category is set! Set one in template.html file!' );}   

  //TOOLBAR
  
    vectorLayer = new OpenLayers.Layer.Vector("vector", { 
                displayInLayerSwitcher: false
            });
            map.addLayer(vectorLayer);

            
            
    toolbar = new mapfish.widgets.toolbar.Toolbar({
                map: map, 
                configurable: false
            });
  
  // WINDOW
  
    // tabs for the center
        var tabs = new Ext.TabPanel({
            region    : 'center',
            margins   : '3 3 3 0', 
            id: 'tab',
            activeTab : 0,
            defaults  : {
				autoScroll : true
			},
            items: [{
                title: mpname,
                xtype: 'mapcomponent',
                map: map
                
            },{
                title    : 'Info',
                html: '<div id="info"</div>',
                id: 'infotable',
                autoScroll: true
             }]
        });

        // Panel for the west
        var nav = new Ext.Panel({
            title       : 'Navigazione',
            
            region      : 'west',
            split       : true,
            width       : 300,
            collapsible : true,
            margins     : '3 0 3 3',
            cmargins    : '3 3 3 3',
            items: [{
                      title: 'Livelli',
                      region: 'north',
                      collapsible: true,
                      autoHeight: true,
                      xtype: 'layertree',
                      map: map
                  },{
                      title: 'Toolbar',
                      collapsible: true,
                      region: 'center',
                      tbar: toolbar                
                      
                  },

                  {
                      title: 'Analisi',
                      region: 'south',
                      collapsible: true,
                      items: [geostatistic]
                      
                      
                  },
                  {
                      title: 'Legenda',
                      region: 'south',
                      collapsible: true,
                      html: '<center id="myChoroplethLegendDiv"></center>'
                      
                      
                  },
                  {
                      title: 'Logo',
                      region: 'south',
                      collapsible: true,
                      height: 85,
                      html: '<center><img src="/SpagoBIGeoReportEngine/js/lib/mapfish/georeport.png" alt="GeoReport"/></center>'
                      
                  }
                  
                  ]
        }); 
      
    
    if (extwindow == "true"){
      
      if ((mapwidth==0) || (mapheight==0)){
      var win = new Ext.Window({
            title    : 'GeoReport',
            closable : true,
            width    : 500,
            height   : 300,
            plain    : true,
            layout   : 'border',
            items    : [nav, tabs]
        });

        win.show();
      
      
      Ext.Msg.alert( 'Status', 'Please set Window dimension (height and width) in your template.html!' );

    }
    else if ((mapwidth!=0) && (mapheight!=0)){
    var win = new Ext.Window({
            title    : 'GeoReport',
            closable : true,
            width    : mapwidth,
            height   : mapheight,
            plain    : true,
            layout   : 'border',
            items    : [nav, tabs]
        });

        win.show();
    
    
    }
    
    }
    else{
    
      var viewport = new Ext.Viewport({
            title    : 'GeoReport',
            closable : true,
            width    : mapwidth,
            height   : mapheight,
            plain    : true,
            layout   : 'border',
            items    : [nav, tabs]
        });

        this.viewport=viewport;

    // });
    
    
    }

initToolbarContent();

} else {
					
          var html = "<table class='header-table-portlet-section'>"+"<tr class='header-row-portlet-section'>"
                     +"<td class='header-title-column-portlet-section'>Insert your credentials correctly!</td>"
                     +"<td class='header-empty-column-portlet-section'>&nbsp;</td>"
                     +"<td class='header-button-column-portlet-section'>"
                     +"<a href='/SpagoBIGeoReportEngine'>"
                     +"<img class='header-button-image-portlet-section' title='Indietro' src='/SpagoBIGeoReportEngine/SpagoBI/logos/img/wapp/back.png' alt='Indietro' />"
                     +"</a></td></tr></table>";

          Ext.Msg.alert('Status','Authentication ERROR'); 
          document.getElementById('error').innerHTML = html;
				}
		    };

		    Sbi.sdk.api.authenticate({ 
				params: {
					user: user
					, password: password
				}
				
				, callback: {
					fn: cb
					, scope: this
				}
			});
     
});
//]]>
</script>
</html>
